package modellayer;

import java.util.ArrayList;
import controllayer.UpdateIncompleteException;

/**
 * The Class ItemContainer.
 * @author
 */
public class ItemContainer {

	/** The instance. */
	private static ItemContainer instance;

	/** The items. */
	private ArrayList<Item> items;

	/**
	 * Instantiates a new item container.
	 */
	private ItemContainer() {
		items = new ArrayList<Item>();
	}

	/**
	 * Gets the single instance of ItemContainer.
	 *
	 * @return single instance of ItemContainer
	 */
	public static ItemContainer getInstance() {
		if (instance == null) {
			instance = new ItemContainer();
		}
		return instance;
	}

	/**
	 * Gets the items.
	 *
	 * @return the items
	 */
	public ArrayList<Item> getItems() {
		return items;
	}

	/**
	 * Gets the amount.
	 *
	 * @param i
	 *            the i
	 * @return the amount
	 */
	public int getAmount(Item i) {
		return i.getAmount();
	}

	/**
	 * Find item.
	 *
	 * @param itemID
	 *            the item id
	 * @return the item
	 */
	public Item findItem(int itemID) {
		Item returnItem = null;
		boolean found = false;
		int size = items.size();
		for (int i = 0; i < size && !found; i++) {
			if (items.get(i).getItemID() == (itemID)) {
				returnItem = items.get(i);
				found = true;
			}
		}
		if (returnItem == null) {
			throw new NullPointerException("Varen blev ikke fundet!");
		}
		return returnItem;
	}

	/**
	 * Removes the item.
	 *
	 * @param itemID
	 *            the item id
	 */
	public void removeItem(int itemID) {
		Item tempI = findItem(itemID);
		if (tempI == null) {
			throw new NullPointerException("Varen blev ikke fundet!");
		}
		items.remove(tempI);
	}

	/**
	 * Update item.
	 *
	 * @param tempI
	 *            the temp i
	 * @param type
	 *            the type
	 * @param newItemID
	 *            the new item id
	 * @param price
	 *            the price
	 * @param amount
	 *            the amount
	 */
	public void updateItem(Item tempI, String type, Integer newItemID,
			Double price, Integer amount) {
		tempI.setItemID(newItemID);
		tempI.setPrice(price);
		tempI.setType(type);
		tempI.setAmount(amount);
		if (tempI.getItemID() != newItemID || tempI.getPrice() != price
				|| tempI.getType().compareTo(type) != 0
				|| tempI.getAmount() != amount) {
			throw new UpdateIncompleteException(
					"Vare blev ikke redigeret korrekt!");
		}
	}

	/**
	 * Creates the item.
	 *
	 * @param type
	 *            the type
	 * @param itemID
	 *            the item id
	 * @param price
	 *            the price
	 * @param amount
	 *            the amount
	 */
	public void createItem(String type, int itemID, Double price, Integer amount) {
		Item i = new Item(type, itemID, price, amount);
		items.add(i);
	}
}